<template>
  <gui-page ref="guiPage" :customHeader="true">
    <!-- 导航 -->
    <template v-slot:gHeader>
      <nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
                      :title="$t('translationImage.FGIn-storage')" @clickRight="clickRight"
                      scanType="1"></nav-bar-custom>
    </template>

    <template v-slot:gBody>
      <view class="barcodeSplitting">
        <!-- 扫描和库位选择模块 -->
        <view class="custom-form-card">
          <view class="custom-card-title">
            <text class="title-line"></text>
            {{ $t('translationImage.In-storageInfo') }}
          </view>
          <view class="custom-card-itemTwo">
            <text class="item-info-title">{{ $t('distributedOut.warehouse') }}：</text>
            <input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
                   v-model="data.warehouse" :placeholder="$t('hardwareOut.pleaseScanMaterial')"/>
            <!-- <superwei-combox style="text-align: right;" :candidates="data.selectList" placeholder="请选择或输入"
              :isJSON="true" keyName="name" v-model="data.warehouse"></superwei-combox> -->
          </view>
          <view class="custom-card-itemTwo" style="padding: 10rpx 0;">
            <text class="item-info-title" style="padding-right: 40rpx;">
              <text
                  class="required-color">*
              </text>
              {{ $t('distributedEnter.barcodeScan') }}
            </text>
            <uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.barcode" type="search"
                           @confirm="confirm" @iconClick="iconClick"
                           :placeholder="$t('pageTranslation.plsScanBarcodeOr')">
            </uni-easyinput>
          </view>
          <view class="custom-card-itemTwo" style="padding: 10rpx 0;">
            <view class="itemTwoMask" v-if="!data.requestParam.materialCode" @click="maskLocationCode">
            </view>
            <text class="item-info-title">
              <text
                  class="required-color">*
              </text>
              {{ $t('distributedOut.location') }}：
            </text>
            <input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
                   v-model="data.locationId"/>
            <!-- <storageBin ref="storageBinRef" :requestBool="data.requestBool"
              :ignoreLocationCode="data.ignoreLocationCode" :defaultValue="data.defaultValue"
              class="gui-text-right"
              v-model="data.locationId"
              requestUrl="/wms/wmsLocationCapacity/recommendedLocationForCCP"
              :requestParam="data.requestParam" @setClick="getClick"></storageBin> -->
          </view>
          <view class="custom-card-itemTwo" style="padding: 10rpx 0">
            <text class="item-info-title">{{ $t('Common.currentTotalCapacity') }}：</text>
            <input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
                   v-model="data.totalQty"/>
          </view>
          <view class="custom-card-itemTwo" style="padding: 10rpx 0">
            <text class="item-info-title">{{ $t('Common.currentRemainingCapacity') }}：</text>
            <input type="text" disabled style="margin: 8rpx 0;text-align: right;" class="gui-form-input"
                   v-model="data.currentCapacitys"/>
          </view>
        </view>
        			<!-- 汇总信息 -->

					<view class="card-boxCustom gui-transition-all  defective-box" style="margin: 20rpx 24rpx 0;"
						v-if="data.list.length">
						<uni-collapse v-model="data.collectShow" style="padding-bottom: 20rpx;">
							<uni-collapse-item titleBorder="none" :show-animation="true">
								<template v-slot:title>
									<view class="custom-card-title">
										<text class="title-line"></text>
										{{ $t('taskList.materialSum') }}
									</view>
								</template>
								<uni-card class="card-my" style="" @click="clickRight">
									<uni-table border stripe emptyText="暂无更多数据" style="max-height: 500rpx;box-sizing: border-box;">
										<!-- 表头行 -->
										<uni-tr class="tableLineHeight">
											<uni-th class="tableLine" width="100">{{ $t("distributedEnter.materialCode")
												}}</uni-th>
											<!-- <uni-th class="tableLine" width="100">{{ $t("translationImage.process")
												}}</uni-th> -->
											<uni-th class="tableLine" width="100">{{ $t("distributedEnter.qty")
												}}</uni-th>
                      <uni-th class="tableLine" width="100">{{ $t("translationImage.numberOfBarcodes")
												}}</uni-th>
										</uni-tr>
										<!-- 表格数据行 -->
										<uni-tr class="tableLineHeight" v-for="(x, i) in tableData.list" :key="i">
											<uni-td class="tableLine">{{ x.materialCode }}</uni-td>
											<!-- <uni-td class="tableLine">{{ x.processCode }}</uni-td> -->
											<uni-td class="tableLine">{{ x.total }}</uni-td>
                      	<uni-td class="tableLine">{{ x.collect }}</uni-td>
										</uni-tr>
									</uni-table>
								</uni-card>
							</uni-collapse-item>
						</uni-collapse>
					</view>
        <!-- card模块 -->
        <!-- <scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll"> -->
        <view v-if="data.scanInfo" class="custom-form-card">
          <uni-collapse v-model="data.value">
            <uni-collapse-item titleBorder="none" :show-animation="true">
              <template v-slot:title>
                <view class="custom-card-title">
                  <text class="title-line"></text>
                  {{ $t('distributedOut.atPresent') }}
                </view>
              </template>
              <view class="content">
                <view class="custom-card-itemOne">
                  <text
                      class="item-info-title">{{ $t('distributedEnter.materialCoded') }}：
                  </text>
                  {{ data.scanInfo.barcode }}
                </view>
                <view class="custom-card-itemOne">
                  <text
                      class="item-info-title">{{ $t('distributedEnter.materialCode') }}：
                  </text>
                  {{ data.scanInfo.materialCode }}
                </view>
                <view class="custom-card-itemOne">
                  <text
                      class="item-info-title">{{ $t('distributedEnter.materialName') }}：
                  </text>
                  {{ data.scanInfo.materialName }}
                </view>
                <view class="custom-card-itemOne">
                  <text
                      class="item-info-title">{{ $t('distributedEnter.materialSpec') }}：
                  </text>
                  {{ data.scanInfo.materialSpec }}
                </view>
                <view class="custom-card-itemOne">
                  <view class="card-item-50">
                    <text
                        class="item-info-title">{{ $t('distributedEnter.qty') }}：
                    </text>
                    {{ data.scanInfo.currentQty }}
                  </view>
                  <view class="card-item-50">
                    <text
                        class="item-info-title">{{ $t('distributedEnter.uom') }}：
                    </text>
                    {{ data.scanInfo.unit }}
                  </view>
                </view>
              </view>
            </uni-collapse-item>
          </uni-collapse>
        </view>
        <!-- </scroll-view> -->
        <!-- 底部确定按钮 -->
        <view class="page-bottom-boxtwo">
          <view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelCommit">
            {{ $t('translationImage.storage') }}
          </view>
        </view>
      </view>
    </template>
  </gui-page>
</template>

<script setup>
import {
  navigate
} from '@/utils/routerSkip.js';
import pdaScan from '@/hooks/pdaScan.js'
import {
  useStore
} from "vuex";
import storageBin from '@/components/storageBin.vue'
import {
  wmsSelectWmsBarcodeInfo,
  productStorage,
  recommendedLocationForCCP, isBarcodeInStock
} from '@/api/api.js'
import {
  basPdaOperationLogFn
} from '@/utils/index.js';
import {
  OPERATION_COMMIT,
  OPERATION_LOOK,
  OPERATION_SCAN
} from '@/constant/index.js'
import {
  ref,
  reactive,
  onMounted,
  watch,
  computed,
  toRaw
} from 'vue';
import {
  onBackPress
} from '@dcloudio/uni-app';
//JS国际化引入
import {
  useI18n
} from 'vue-i18n';
import tableColor from '@/hooks/tableColor.js'

const {
  t
} = useI18n();
const {
  scan
} = pdaScan()
components: {
  storageBin
}
const storageBinRef = ref(null)
let data = reactive({
  requestBool: false, //库位是否直接请求的标识
  defaultValue: '', //默认库位
  value: ['0'],
  warehouse: t('pageTranslation.warehouseOfFG'), //仓库
  currentLocationInfo: {}, // 当前选择库位信息
  locationUseList: [], //
  scanInfo: undefined, //当前扫描数据
  locationId: '', //仓库 locationCode
  requestParam: {
    warehouseCode: 'FG',
    materialCode: '', // 物料code
    selectType: 'CCP'
  },
  barcodeList: [],
  seat: '', //库位
  barcode: '', //条码
  ignoreLocationCode: [], //前端算满的库位
  currentTotal: null, //当前总容量
  currentCapacitys: null, // 当前剩余容量
  firstLocation: true, //第一次请求库位
  totalQty: null, //当前
  list:[],
	collect:[],
	barcodeList: [],//扫描的条码数组
})
/**
 * 1.默认为成品仓
 * 2.库位为成品仓下面的库位 接口传
 * 3.判断当前扫码是否属于成品仓
 * 4.扫码输入数量是否超出库位容量
 */
let { tableData } = tableColor();
const { cellStyle, cellHeaderStyle } = tableColor();
const locationInput = ref()
let store = useStore();
onMounted(() => {
  console.log('开始监听PDA扫码')
  uni.$on('scancodedate', (data) => {
    console.log('获取到的code：' + data.code)
    getCode(data.code, 'pda')
  })

  uni.$on('addInventoryCount', () => {
    data.currentCapacitys = Number(data.currentTotal) - data.barcodeList.length;
  })
  try {
    let inputParameter = '无'
    let returnParameter = '无'
    let operationPicture = '成品入库'
    let callInterface = '无'
    let opertionParmes = {
      inputParameter,
      returnParameter,
      operationPicture,
      callInterface,
      responseCode: '无', //返回状态
      errorMessage: '无', //错误信息
      isPass: 'Y', //是否成功 Y N
      operationType: OPERATION_LOOK
    }
    basPdaOperationLogFn(opertionParmes)
  } catch (error) {
  }
  // locationCode()
})
data.barcodeList = computed(() => {
  return store.state.finishedProductStorageList
})
// 物料信息汇总 
const collect = () => {
	data.collect = ['0']
	let list = Object.values(data.barcodeList)
	let dataInfo = {};
  
	list.forEach((item, index) => {
		let { materialCode } = item;
		// 扫描的物料按照物料号分类
		if (!dataInfo[materialCode]) {
			dataInfo[materialCode] = {
				materialCode,
				child: []
			}
		}
		dataInfo[materialCode].child.push(item)
		// 扫描的物料号分类的总数用量
		dataInfo[materialCode].total = dataInfo[materialCode].child.reduce((pre, cur) => {
			// 全部调拨
			return pre + cur.currentQty;
		}, 0)
		// 物料条码个数
		dataInfo[materialCode].collect = dataInfo[materialCode].child.length

	});
	data.list = Object.values(dataInfo);
	tableData.list = data.list
	console.log(data.list,'======')
}


onBackPress((options) => {
  if (options.from == 'backbutton') {
    navBackCheck()
    return true;
  }
})
//导航栏左侧返回
const clickLeftBack = () => {
  navBackCheck()
}
const navBackCheck = () => {
  if (!data.barcodeList.length) {
    uni.navigateBack({
      delta: 1
    });
    return true
  }
  uni.showModal({
    title: t('smashRemoval.warmPrompt'),
    content: t('materials.unsubmittedDataIn'),
    success: function (res) {
      if (res.confirm) {
        store.commit('reactFinishedProductStorage')
        uni.navigateBack({
          delta: 1
        });
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    }
  });
  return true
}
// 计算库位逻辑
const calculateLocationCode = (newVal) => {
  let tepData = toRaw(newVal)
  console.log(newVal)
  if (!tepData.length) {
    data.scanInfo = undefined
    data.barcode = ''
    data.requestParam.materialCode = ''
  }
  if (!data.scanInfo && tepData.length) {
    data.scanInfo = tepData[0]
    data.barcode = data.scanInfo.barcode
    data.requestParam.materialCode = data.scanInfo.materialCode
  }
  // 先清空,后续追加
  data.locationUseList.forEach(l => {
    l.barcodeList = []
  })
  // 追加
  tepData.forEach(x => {
    data.locationUseList.forEach(k => {
      if (x.locationCode == k.locationCode) {
        k.barcodeList.push(x.barcode)
        k.surplusCapacity = k.currentCapacity - k.barcodeList.length
      }
    })
  })
  //算满库位变量置空
  data.ignoreLocationCode = []
  // 把前端预算容量算出为0的库位抽出
  data.locationUseList.forEach(x => {
    if (x.surplusCapacity == 0) {
      data.ignoreLocationCode.push(x.locationCode)
    }

  })


}
//把扫描条码变为物料集合的二维数组
watch(() => data.barcodeList, (newVal, oldVal) => {
  calculateLocationCode(newVal)
  collect()
  if (data.locationId) {
    //全局消息总线
    //uni.$emit('reduceInventoryCount',{locationId:data.locationId,count: data.barcodeList.length})
  }
}, {
  immediate: true,
  deep: true
});

// 推荐库位
const locationCode = () => {
  recommendedLocationForCCP({
    warehouseCode: 'FG',
    materialCode: data.materialCode, // 物料code
    selectType: 'CCP'
  }).then(res => {
    if (res.status == 200) {
      let x = res.data.rows[0]
      getClick(x)
    } else {
      store.commit('deleteFinishedProductStorageByBarcode', data.barcode)
      uni.showToast({
        title: t('Common.confirmTheRecommended'),
        icon: 'none'
      })
      return
    }
  })
}

// 获取选中的库位id
const getClick = (x) => {
  data.currentLocationInfo = x;
  data.locationId = x.locationCode;
  data.currentTotal = x.maxCapacity - x.usedInventory;
  data.totalQty = x.maxCapacity;


  data.currentCapacitys = Number(data.currentTotal) - data.barcodeList.length;
  if (data.currentCapacitys < 0 && data.barcodeList.length && data.currentTotal != null) {
    data.currentCapacitys = 0
    store.commit('deleteFinishedProductStorageByBarcode', data.barcode)
    uni.showToast({
      title: t('JsInternational.volumn'),
      icon: 'none'
    })
    return
  }

  judgeBarcode()
  if (data.locationId) {
    //全局消息总线
    uni.$emit('reduceInventoryCount', {
      locationId: data.locationId,
      count: data.barcodeList.length
    })
  }
  // var  usecount=data.locationUseList.filter(x => x.locationCode === data.locationId).length
  // data.currentTotal=x.maxCapacity-x.usedInventory;
  // data.currentCapacitys=data.currentTotal-1;

}
const maskLocationCode = () => {
  uni.showToast({
    title: t('pageTranslation.plsChooseLabelFirstly'),
    icon: 'none'
  })
  return
}
// 用户点击扫码图标
const iconClick = async (type) => {
  if (type === 'suffix') {
    let code = await scan()
    getCode(code, 'scan')
  }
}
// 用户点击搜索
const confirm = () => {
  getCode(data.barcode, 'keydown')
}
// 获取code
const getCode = (code, type) => {
  // 判断这个托盘本次有没有绑定过
  let arr = data.barcodeList.filter(x => x.barcode == code);
  if (arr.length > 0) {
    uni.showToast({ title: t('smashRemoval.codesRepeatedly'), icon: 'none' });
    return
  }
  let isBind = data.barcodeList.some(x => x.barcode == code);
  if (isBind) {
    uni.showToast({
      title: t('JsInternational.scanned'),
      icon: 'none'
    })
    return
  }
  if (!data.warehouse) {
    uni.showToast({
      title: t('pageTranslation.plsChooseWarehous'),
      icon: 'none'
    })
    return
  }
  if (!code) {
    uni.showToast({
      title: t('stockManage.pleaseScanCode'),
      icon: 'none'
    })
    return
  }
  data.scanValue = code
  let parmes = {
    isSp: 0,
    barcode: code,
    selectType: 'productStorage',
    warehouseCode: 'FG',
  }
  uni.showLoading({
    title: 'loading',
    mask: true
  });

  wmsSelectWmsBarcodeInfo(parmes).then(res => {
    //隐藏加载框
    uni.hideLoading();
    try {
      let inputParameter = JSON.stringify(parmes)
      let returnParameter = JSON.stringify(res)
      let operationPicture = '成品入库'
      let callInterface = res.rquestUrl
      let opertionParmes = {
        inputParameter,
        returnParameter,
        operationPicture,
        responseCode: res.status, //返回状态
        errorMessage: res.message, //错误信息
        isPass: res.status == 200 ? 'Y' : 'N', //是否成功 Y N
        callInterface,
        operationType: OPERATION_SCAN
      }
      basPdaOperationLogFn(opertionParmes)
    } catch (error) {
    }
    console.log(res)
    if (res.status == 200) {
      // 成品入库每批次只能入库同一种物料
      let materialCode = res.data.materialCode;
      if (data.barcodeList.length == 0) {

      } else {
        var existMaterialCode = data.barcodeList.some(e => e.materialCode == materialCode)
        if (!existMaterialCode) {
          uni.showToast({
            title: t('stockManage.fgInstore'),
            icon: 'none'
          })
          return
        }
      }
      data.scanInfo = res.data
      data.requestParam.materialCode = res.data.materialCode
      data.materialCode = res.data.materialCode
      store.commit('addFinishedProductStorage', data.scanInfo)
      data.requestBool = true
      locationCode()
    } else {

     if(res.message.indexOf('packaging')!== -1||res.message.indexOf('打包')!== -1){ //提示的是成品补录
		 uni.showModal({
		   title: t('Common.prompt'),
		   content: res.message,
		   confirmText: t('Common.correct'),
		   showCancel: true,
		 		cancelText:t('Common.cancel'),
		   success: function (res) {
		     if (res.confirm) {
		          uni.navigateTo({
		          	url:'/pages/barcodeManagement/finishedProductAdditional?barcode='+data.scanValue
		          })
		     } else if (res.cancel) {
		 
		     }
		   }
		 });
	 }else{
		 
		 uni.showModal({
		   title: t('Common.prompt'),
		   content: res.message,
		   confirmText: 'Close',
		   showCancel: false,
		 		
		   success: function (res) {
		     if (res.confirm) {
		        
		     } else if (res.cancel) {
		 
		     }
		   }
		 });
	 }
    

    }
  })
}
// 判断 Barcode
const judgeBarcode = () => {
  let isTrue = data.locationUseList.some(x => x.locationCode === data.locationId)
  if (!isTrue) {
    data.locationUseList.push({
      locationCode: data.currentLocationInfo.locationCode, //库位code
      surplusCapacity: Number(data.currentLocationInfo.maxCapacity) - Number(data.currentLocationInfo
          .usedInventory), //后端告诉前端容量
      barcodeList: [] //当前库位本次扫描绑定的barcode条码集合
    })
  }

}
//扫描纪录
const clickRight = () => {
  navigate({
    url: '/pages/barcodeManagement/productInventoryRecord'
  })
}

/**
 * 提交数据
 */
function commitData () {
  let tepData = toRaw(data.barcodeList)
  let parmes = {
    warehouseCode: 'FG',
    wmsBarcodeList: []
  }
  tepData.forEach(x => {
	  if(!parmes.wmsBarcodeList.some(e=>e.barcode== x.barcode))
	  {
		  parmes.wmsBarcodeList.push({
		    id: x.id, // 条码的id
		    locationCode: data.locationId, // 仓库code
		    warehouseCode: 'FG',
		    barcode: x.barcode
		  })
	  }
  });
  uni.showLoading({
    title: 'loading',
    mask: true
  });
  productStorage(parmes).then(res => {
    //隐藏加载框
    uni.hideLoading();
    try {
      let inputParameter = JSON.stringify(parmes)
      let returnParameter = JSON.stringify(res)
      let operationPicture = '成品入库'
      let callInterface = res.rquestUrl
      let opertionParmes = {
        inputParameter,
        returnParameter,
        operationPicture,
        callInterface,
        responseCode: res.status, //返回状态
        errorMessage: res.message || '无', //错误信息
        isPass: res.status == 200 ? 'Y' : 'N', //是否成功 Y N
        operationType: OPERATION_COMMIT
      }
      basPdaOperationLogFn(opertionParmes)
    } catch (error) {
    }
    if (res.status == 200) {
      //删除已提交的数据
      uni.showToast({
        title: t('smashRemoval.submitSuccessfully'),
        icon: "none"
      });
      store.commit('reactFinishedProductStorage')
      console.log(data.barcodeList)
      uni.redirectTo({
        url: '/pages/barcodeManagement/finishedProductInventory'
      });
    } else {
      uni.showToast({
        title: res.message,
        duration: 3000,
        icon: "none"
      });
    }
  })
}

// 提交操作
const handelCommit = () => {
  // 1.判断是否有数据
  if (!data.barcodeList.length) {
    uni.showToast({
      title: t('stockManage.pleaseScanCode'),
      icon: 'none'
    })
    return
  }
  // 2. 判断是否有库位
  if (!data.locationId) {
    uni.showToast({
      title: t('pageTranslation.plsChooseLocatoinFirstly'),
      icon: 'none'
    })
    return
  }
  // 3.判断是否存在已入库的barcode
  const barcodeArr = data.barcodeList.map(item => item.barcode);
  isBarcodeInStock(barcodeArr).then((res) => {
    if (res?.statusCode === 200) {
      const storedData = res?.data || []
      if(storedData.length === 0) {
        // 无需过滤数据 直接提交
        commitData();
      }else{
        uni.showModal({
          title: t("Common.prompt"),
          content: t('stockManage.commitConfirmContent', { barcode: storedData.join(",") }),
          confirmText: t('Common.continue'),
          cancelText: t('Common.cancel'),
          success: function (res) {
            // 用户点击了确认
            if (res.confirm) {
              // 过滤掉barcodeArr中已提交的数据
              commitData();
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      }
    }
  })
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 88rpx);
  // height: 100vh;
}

.distributed-head {
  border-bottom-left-radius: 16rpx;
  border-bottom-right-radius: 16rpx;
}

.scroll {
  flex: 1;
  height: 2rpx;
}

.custom-card-itemTwo {
  position: relative;
}

.itemTwoMask {
  position: absolute;
  left: 0px;
  top: 0px;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.tableLineHeight {
	height: 60rpx;
	min-width: 630rpx !important;
}

.tableLine {
	padding: 0 20rpx !important;
	box-sizing: border-box;
}

.uni-table-loading {
	height: 60rpx !important;
}
</style>
